package io.renren.modules.jxgk.service;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/webSocket")
public class WebSocket {

    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSocketSet=new CopyOnWriteArraySet<>();
    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        webSocketSet.add(this);
        //有新的链接
    }
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        //链接断开
    }
    @OnMessage
    public void onMessage(String message){

    }
    public void sendMessage(String message){
        for(WebSocket webSocket:webSocketSet){
            try{
                webSocket.session.getBasicRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

}
